// pages/guidanceStudy/myCertificate/myCertificate.js

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ratio: 1,
    btnType: false,
    alertType: false,
    second: 10,
    submitType: true,
    logo: '',
    qr_code: '',
    status: '',
    wx_head: '',
    wx_name: '',
    shareTempFilePath: '',
    showDialog: false,
    id_number: '',
    isShowGetUserInfo: false
  },

  //授权获取个人头像和昵称
  getUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        'isShowGetUserInfo': false
      })
      wx.setStorageSync('wx_head', e.detail.userInfo.avatarUrl);
      wx.setStorageSync('wx_name', e.detail.userInfo.nickName);
      wx.login({
        success: res => {
          wx.setStorageSync('code', res.code);
          this.parseUnionID(e.detail.encryptedData, e.detail.iv);
        }
      })
      wx.showToast({
        title: '获取个人信息成功',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '个人信息授权失败',
        icon: 'none'
      });
      wx.redirectTo({
        url: 'pages/guidanceStudy/fuli/fuli'
      });
    }
  },
  //授权
  getSetting() {
    wx.getSetting({
      success: res => {
        //没授权过
        if (!res.authSetting['scope.userInfo']) {
          wx.hideLoading();
          this.setData({
            isShowGetUserInfo: true
          })
        } else {
          this.isRegister(wx.getStorageSync('union_id'));
        }
      }
    })
  },
  /**
   * 解析unionID
   */
  parseUnionID(encryptedData, iv) {
    wx.showLoading({
      title: '拼命加载中...',
    });
    wx.request({
      url: app.globalData.url + 'c=home&m=getPhoneNumber',
      data: {
        'encryptedData': encryptedData,
        'iv': iv,
        'code': wx.getStorageSync('code')
      },
      success: (res) => {
        res = res.data;
        if (res.status == 200) {
          //保存unionID到本地
          // var phone = res.data.purePhoneNumber;
          var union_id = res.data.unionId;
          wx.setStorageSync('union_id', union_id);
          this.isRegister(union_id);
        } else {
          wx.showToast({
            title: '获取个人信息失败，请重试',
            icon: 'none'
          })
          this.setData({
            getPhoneNumberChange: true
          })
        }
      }
    })
  },
  //判断unionID是否注册
  isRegister(union_id) {
    wx.request({
      url: app.globalData.url + 'c=user&m=isRegister',
      data: {
        union_id: union_id
      },
      success: res => {
        wx.hideLoading();
        res = res.data;
        if (res.status == 200) {
          if (res.data.is_register != 0) {
            //已注册
            wx.setStorageSync('user_id', res.data.user_id);
            app.globalData.userId = res.data.user_id;
            wx.request({
              url: app.globalData.url + 'c=user&m=myCertificate',
              data: {
                user_id: wx.getStorageSync('user_id'),
              },
              success: res => {
                res = res.data;
                if (res.status === 200) {
                  this.setData({
                    logo: res.data.logo,
                    qr_code: res.data.qr_code,
                    status: res.data.status,
                    wx_head: res.data.wx_head,
                    wx_name: res.data.agent_name,
                    id_number: res.data.id_number
                  })
                  this.getImage();
                  //上传头像和手机号码
                  wx.request({
                    url: app.globalData.url + 'c=user&m=keepWeChat',
                    data: {
                      user_id: res.data.id,
                      wx_head: wx.getStorageSync('wx_head'),
                      wx_name: wx.getStorageSync('wx_name')
                    },
                    success: res => {
                      wx.hideLoading();
                      res = res.data;
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none'
                  })
                }
              }
            });
          } else {
            wx.redirectTo({
              url: '/pages/welcome/applydesc/applydesc'
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中',
    });
    if (wx.getStorageSync('user_id')) {
      wx.request({
        url: app.globalData.url + 'c=user&m=myCertificate',
        data: {
          user_id: wx.getStorageSync('user_id'),
        },
        success: res => {
          res = res.data;
          if (res.status == 200) {
            this.setData({
              logo: res.data.logo,
              qr_code: res.data.qr_code,
              status: res.data.status,
              wx_head: res.data.wx_head,
              wx_name: res.data.agent_name,
              id_number: res.data.id_number
            })
            this.getImage();
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        }
      })
    }else{
      this.getSetting();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 获取图片
   */
  getImage: function() {
    wx.getImageInfo({
      src: this.data.logo,
      success: img1 => {
        wx.getImageInfo({
          src: this.data.wx_head,
          success: img2 => {
            wx.getImageInfo({
              src: this.data.qr_code,
              success: img3 => {
                this.drawImg(img1, img2, img3);
              }
            })
          }
        })
      }
    });
  },

  /**
   * canvas绘制
   */
  drawImg: function(img1, img2, img3) {
    var context = wx.createCanvasContext('share');
    let canvasWidthPx = 620 / this.data.ratio;
    let canvasHeightPx = 1057 / this.data.ratio;
    context.fillStyle = '#ffffff';
    context.fillRect(0, 0, canvasWidthPx, canvasHeightPx);
    context.drawImage("/images/certificate-bg-big.png", 0, 0, canvasWidthPx, canvasHeightPx);

    let img1X = (620 - img1.width) / this.data.ratio / 2;
    let img1Y = 95 / this.data.ratio;
    context.drawImage(img1.path, img1X, img1Y, img1.width / this.data.ratio, img1.height / this.data.ratio);

    context.save();
    context.beginPath();
    context.arc(310 / this.data.ratio, 300 / this.data.ratio, 70 / this.data.ratio, 0, Math.PI * 2, false);
    context.setStrokeStyle('#e0e0e0');
    context.stroke();
    context.clip();
    context.drawImage(img2.path, 480 / this.data.ratio / 2, 230 / this.data.ratio, 140 / this.data.ratio, 140 / this.data.ratio);
    context.restore();

    context.drawImage('/images/avatar-bg-active-big.png', 167 / this.data.ratio, 195 / this.data.ratio, 286 / this.data.ratio, 235 / this.data.ratio);
    context.setFontSize(28 / this.data.ratio);
    context.setTextAlign('center');
    context.setFillStyle('#999999');
    context.fillText(this.data.wx_name, 310 / this.data.ratio, 475 / this.data.ratio);
    context.fillText('顾问编号：' + this.data.id_number, 310 / this.data.ratio, 515 / this.data.ratio);

    let authUrl;
    let tagWidth = 154;
    let tagLeft = 233;
    if (this.data.status == 0) {
      authUrl = '/images/not-authentication.png';
    } else if (this.data.status == 1) {
      authUrl = '/images/authentication.png';
    } else {
      authUrl = '/images/no-authentication.png';
      tagWidth = 202;
      tagLeft = 209;
    }
    context.drawImage(authUrl, tagLeft / this.data.ratio, 600 / this.data.ratio, tagWidth / this.data.ratio, 36 / this.data.ratio);

    let img3X = 235 / this.data.ratio;
    let img3Y = 820 / this.data.ratio;
    context.drawImage(img3.path, img3X, img3Y, 150 / this.data.ratio, 150 / this.data.ratio);
    context.setStrokeStyle('#e5e5e5');
    context.strokeRect(230 / this.data.ratio, 815 / this.data.ratio, 160 / this.data.ratio, 160 / this.data.ratio);

    context.draw(false, this.getTempFilePath);
    this.setData({
      btnType: true
    });
  },

  /**
   * 获取临时路径
   */
  getTempFilePath: function() {
    wx.canvasToTempFilePath({
      canvasId: 'share',
      success: (res) => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        })
        wx.hideLoading();
      }
    })
  },

  /**
   * 保存相册
   */
  saveImageToPhotosAlbum: function() {
    var that = this;
    if (!this.data.shareTempFilePath) {
      wx.showModal({
        title: '提示',
        content: '图片绘制中，请稍后重试',
        showCancel: false
      })
    }
    wx.getSetting({
      success(res) {
        console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.save();
            },
            fail(err) {
              console.log(err);
              that.setData({
                'showDialog': true
              })
            }
          })
        } else {
          that.save();
        }
      }
    })
  },

  save: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareTempFilePath,
      success: (res) => {
        this.setData({
          alertType: true
        })
        this.waitTime();
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },

  /**
   * 倒计时
   */
  waitTime: function() {
    let s = this.data.second;
    var timer = setInterval(() => {
      s--;
      if (s == 0) {
        clearInterval(timer);
        timer = null;
        this.setData({
          submitType: false
        })
      } else {
        this.setData({
          second: s
        });
      }
    }, 1000);

    // setTimeout(this.waitTime, 1000);
  },


  /**
   * 关闭弹窗
   */
  closeAlert: function() {
    this.setData({
      alertType: false,
      submitType: true,
      second: 10
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.showDialog) {
      this.setData({
        'showDialog': false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})